const funApi = require('./router/bds/funcApi.js');
const Response = require("./class/Response.js");
// 注册PAPI

function registerPAPI(){
    PAPI.registerServerPlaceholder(funApi.getOnlinePlayersNum, 'CoordinationWss', 'onlinePlayersNum'); // 协调服务端在线玩家人数
    PAPI.registerServerPlaceholder(funApi.getOnlinePlayersName, 'CoordinationWss', `onlinePlayersName`); // 协调服务端在线玩家列表
}

// 获取信息接口
function getOnlineClientsInfo(){
    let res = new Response();
    res.header.url = '/bds/getOnlineClientsInfo';
    res.body.data = {};
    sendJson(res.json);
}

// 发送不同种类的请求
function sendJson(){
    
}

function sendJsonBDS(json, bdsUuid){
    sendJson(json);
}

function sendJsonMainBDS(json){
    sendJson(json);
}

function broadcastJson(json){
    WSC.client.sendJson(json);
}

function sendServerLogger(msg, level='info'){
    return WSC.client.sendServerLogger(msg, level);
}

ll.exports(sendServerLogger, 'CoordinationWss', 'sendServerLogger');

// 接收数据接口
WSC.get('/llapi/data', (wsclient, req, res)=>{
    // 接收服务端数据，发送给各插件
    WSC.api.listener.emit('data', res.json);
});

WSC.api.listener.on('chat', (json)=>{
    if (CONF.CONFIG.get('Chat')['ConsoleDisplay'] == true){ 
        let sender = json.body.sender;
        let msg = json.body.message;
        let serverName = json.header.source_bds_serverName;
        let time = json.body.time;
        if (mc.getPlayer(sender) != null && !CONF.CONFIG.get('Chat')["ConsoleDisplayLocal"]){
            return;
        }
        WSC.logger.info(`[${serverName}]<${sender}> ${msg}`);
    }
});



//================================
// 注册协调服务端所有事件
for (let eventName in WSC.api.remoteCallFunctions){
    WSC.api.listener.on(eventName, (...args)=>{
        for (let namespace in WSC.api.remoteCallFunctions[eventName]){
            for (let name in WSC.api.remoteCallFunctions[eventName][namespace]){
                WSC.api.remoteCallFunctions[eventName][namespace][name](...args);
            }
        }
    });
}

/**
 * @description: 注册外部监听器回调
 * @param {string} eventName 监听的事件名
 * @param {string} namespace 导出函数的命名空间, 一般设为插件名
 * @param {string} name 导出函数的名称
 * @return {boolean} 监听器回调是否注册成功
 */
function registerListenerCall(eventName, namespace, name){
    // 无此api返回false
    if (!(eventName in WSC.api.remoteCallFunctions)){
        return false;
    }
    // 导入外部回调
    if (WSC.api.remoteCallFunctions[eventName][namespace] == undefined){
        WSC.api.remoteCallFunctions[eventName][namespace] = {[name]: ll.import(namespace, name)};
    }else{
        WSC.api.remoteCallFunctions[eventName][namespace][name] = ll.import(namespace, name);
    }
    return true;
}

ll.exports(registerListenerCall, 'CoordinationWss', 'registerListenerCall');


module.exports = {
    registerPAPI
};
